package com.hw.utils;

import java.io.IOException;
import java.net.SocketException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.tools.ant.taskdefs.Get;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.hw.dagl.model.Ftp;

public class FtpUtil {
	
	public static final Log logger =  LogFactory.getLog(FtpUtil.class);
	
	
	  //private static FTPClient fc = null;
	  static Ftp ftp = new Ftp();
	  
	  /**
	   * 获取ftp连接
	   * @param IP
	   * @param port
	   * @param destpath
	   * @param username
	   * @param password
	 * @throws IOException
	 * @throws SocketException
	   */
	public  static FTPClient ftpConnection(FTPClient fc,String IP,int port,String destpath,String username,String password) throws SocketException, IOException {

			 fc=new FTPClient();
			 fc.setControlEncoding("GBK");//必须设置在connect之前，不然无法复制文件(含有中文)，设置编码也不行
			 fc.connect(IP,port);
			 fc.login(username, password);			 
			// FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
			// conf.setServerLanguageCode("zh");
			 fc.setFileType(FTP.BINARY_FILE_TYPE);
			//boolean flag= fc.changeWorkingDirectory(destpath); 
			 
	         if (!FTPReply.isPositiveCompletion(fc.getReplyCode())) {
	             fc.disconnect();
	             logger.info("连接服务器失败");
	             //System.exit(1);
	         }
		return fc;
 }
	/**
	 * 关闭ftp连接
	 */
	public static  void closeFtp(FTPClient fc){
		if (fc!=null && fc.isConnected()){
			try {
				fc.logout();
				fc.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static boolean changeWorkingDirectory(FTPClient ftpClient, String dir){
		boolean bool=false;
    //判断目录是否存在  
    try {
		if(ftpClient.changeWorkingDirectory(dir)) {  
		    //目录已存在，无需创建  
		    bool = true;  
		}else {  
		    //目录不存在，创建目录  
		    if(createMultiDirectory(ftpClient, dir)) {  
		        try {
					if(ftpClient.changeWorkingDirectory(dir)) {  
					    bool = true;                              
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  
		    }  
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return bool;
	}
	   private static boolean createMultiDirectory(FTPClient ftpClient,String multiDirectory) {  
	        boolean bool = false;  
	        try {  
	            String[] dirs = multiDirectory.split("/");  
	            ftpClient.changeWorkingDirectory("/");  
	              
	            //按顺序检查目录是否存在，不存在则创建目录  
	            for(int i=1; dirs!=null&&i<dirs.length; i++) {  
	                if(!ftpClient.changeWorkingDirectory(dirs[i])) {  
	                    if(ftpClient.makeDirectory(dirs[i])) {  
	                        if(!ftpClient.changeWorkingDirectory(dirs[i])) {  
	                            return false;  
	                        }  
	                    }else {  
	                        return false;                         
	                    }  
	                }  
	            }  	              
	            bool = true;  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }
			return bool; 
	    }
	
	/**
	 * 初始化ftp参数
	 * @return
	 */
	public static Ftp  ftpConfig(){		
		Properties pro = new Properties();
		try {
			pro= PropertiesLoaderUtils.loadAllProperties("application.properties");
		} catch (IOException e) {
			e.printStackTrace();
		}
		ftp.setIpAddr(pro.getProperty("ftp_ip"));
		ftp.setPort(Integer.parseInt(pro.getProperty("ftp_port")));
		ftp.setUserName(pro.getProperty("ftp_username"));
		ftp.setPwd(pro.getProperty("ftp_password"));
		ftp.setDestpath(pro.getProperty("ftp_destpath"));
		ftp.setHttpAddr(pro.getProperty("http_prefix"));
		ftp.setDestpath2(pro.getProperty("ftp_destpath2"));
		ftp.setHttpAddr2(pro.getProperty("http_prefix2"));
		return ftp;
	}
	
	public static void main(String args[]){
		/*Ftp ftp = ftpConfig();
		System.out.println(ftp.getIpAddr()+ ftp.getPort()+ftp.getDestpath()+ftp.getUserName()+ftp.getPwd());
		FTPClient ftpclient = ftpConnection(ftp.getIpAddr(), ftp.getPort(),ftp.getDestpath(),ftp.getUserName(),ftp.getPwd());
		changeWorkingDirectory(ftpclient,"/20170610/12312312/");*/
		
	}
}
